//
//  ContractListVC.m
//  NtoccShipper
//
//  Created by mac on 2019/12/27.
//  Copyright © 2019 zhuchongjin. All rights reserved.
//

#import "ContractListVC.h"
#import "ContractListCell.h"
#import "ContractListModel.h"
#import "CJWKWebViewVC.h"
#import "CJAlertViewNoTitle.h"
#import "CJAlertViewSign.h"
@interface ContractListVC ()<UITableViewDelegate,UITableViewDataSource>{
    FlexFrameView *header;
}
@property (nonatomic,strong) CJTableView *tableView;
@property (nonatomic,strong) NSMutableArray *modelArray;
@property (nonatomic,strong) NSString *refreshType; //刷新
@property (nonatomic,readwrite) int page;
@property (nonatomic,strong) CJTextField *fieldSerach;
@end

@implementation ContractListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setTitleName:CJLString(@"合同列表")];
    [self setBackLeftButton:@""];
    [self createTopSearchView];
    [self.view addSubview:self.tableView];
    WS(ws);
    self.tableView.placeHolderView = [[KKTableViewNoDataView alloc] initWithFrame:self.tableView.bounds image:[UIImage imageNamed:@"no_data"] viewClick:^{
           [ws.tableView.mj_header beginRefreshing];
    }];
    [self initData];
    [self loadData];
}

- (void)createTopSearchView{
    
    CGRect rcFrame = CGRectMake(0, kTopHeight, [[UIScreen mainScreen] bounds].size.width, 0);
    header = [[FlexFrameView alloc] initWithFlex:@"ContractListSearchView" Frame:rcFrame Owner:self];
    header.flexibleHeight = YES;
    [header layoutIfNeeded];
    [self.view addSubview:header];
}

- (void)btnSerachRouteView{
    if ([CJRegular getIsStrEmpty:self.fieldSerach.text]) {
        self.fieldSerach.text = @"";
    }
    [self.tableView.mj_header beginRefreshing];
}

- (void)initData{
    self.modelArray = [[NSMutableArray alloc]init];
    self.page = 1;
    self.fieldSerach.text = @"";
}

/// <#Description#>
- (void)loadData {

    NSString *strUrl = CJStringWithFormat(@"%@/ntocc-basic-api/orderDetailContract",CJBaseUrl);
    NSDictionary *dicPra = @{@"pageNum":CJStringWithFormat(@"%d",self.page),
                             @"pageSize":@"10",
                             @"searchInfo":self.fieldSerach.text,
                             @"contractType":@"1"  //合同类型，0承运，1托运
    };
    WS(ws);
    [[HDNetworking sharedHDNetworking] GET:strUrl parameters:dicPra success:^(id  _Nonnull responseObject) {

        DLog(@"++++++++%@",responseObject);
        NSArray *list = responseObject[@"records"];
        NSString *total = CJStringWithFormat(@"%@",responseObject[@"total"]);
//        if (list.count > 0) {

           if ([ws.refreshType isEqualToString:@"down"]) {
               [ws.modelArray removeAllObjects];
           }

           NSError * error ;
           NSArray *arr = [ContractListModel arrayOfModelsFromDictionaries:list error:&error];
           [ws.modelArray addObjectsFromArray:arr];

           [ws.tableView.mj_header endRefreshing];
           [ws.tableView.mj_footer endRefreshing];

           if (ws.modelArray.count == total.intValue) {
               [ws.tableView.mj_footer endRefreshingWithNoMoreData];
           }
//        }else{
//           [ws.modelArray removeAllObjects];
//           [ws.tableView.mj_header endRefreshing];
//           [ws.tableView.mj_footer endRefreshingWithNoMoreData];
//        }
        [ws.tableView reloadData];

    } failure:^(NSError * _Nonnull error) {
        DLog(@"++++++++%@",error);
        [ws.tableView.mj_header endRefreshing];
        [ws.tableView.mj_footer endRefreshing];
    }];
}

- (void)downRefresh{
    self.refreshType = @"down";
    self.page = 1;
    [self loadData];
}

- (void)upRefresh{
    self.refreshType = @"up";
    self.page ++;
    [self loadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.modelArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    WS(ws);
    static NSString *identifier = @"ContractListCell";
    ContractListCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[ContractListCell alloc] initWithFlex:[CJControl getUIWithNew] ? @"ContractListCellNew":@"ContractListCell" reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    ContractListModel *model = self.modelArray[indexPath.row];
    [cell setCellInfoWithModel:model];

    cell.blockElectrSign = ^(id anyObject) {
        [ws btnElectrSignActionWithModel:ws.modelArray[indexPath.row]];
    };
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ContractListModel *model = self.modelArray[indexPath.row];
    
    if ([CJRegular getIsStrEmpty:model.contractPath]) {
    }else{
        CJWKWebViewVC *vc = [CJWKWebViewVC new];
        vc.strUrl = model.contractPath;
        vc.strTitle = @"合同详情";
        [self pushVc:vc];
    }
}

#pragma mark ---------- btnAction
/// 电子签章
/// @param model <#model description#>
- (void)btnElectrSignActionWithModel:(ContractListModel *)model{
    DLog(@"电子签章");
    WS(ws);
    if ([CJControl getElecSignTypeByAouthCode]) {
        [self getElecSignTypeWithAouthCodeModel:model];
    }else{

        CJAlertViewNoTitle *alert = [[CJAlertViewNoTitle alloc]initWithContent:@"确定生成电子签章吗？" ClickOnSure:^(NSString * _Nonnull strSure) {
             [ws getElecSignTypeWithOrderCode:model.code];
        } ClickOnCancle:^(NSString * _Nonnull strCancle) {

        }];
        alert.center=self.view.center;
        WLAlertView * alertView = [[WLAlertView alloc]init];
        alertView.containerView = alert;
        alertView.isTouchOtherUndissmiss = YES;
        [alertView show];
    }
}

#pragma mark ----------短信验证

- (void)getElecSignTypeWithAouthCodeModel:(ContractListModel *)model{
    
    NSArray *listTitle = @[@"货源单号",@"运单编号",@"手机号",@"验证码"];
    NSArray *listContent = @[
        [CJControl getThreeUnaryValueStr:model.mainOrderNumber],
        [CJControl getThreeUnaryValueStr:model.orderCode],
        [CJControl getThreeUnaryValueStr:model.orderCreatedPhone],
        [CJControl getThreeUnaryValueStr:model.code]
    ];

    WS(ws);
//    CJAlertViewSign *alert = [[CJAlertViewSign alloc]initWithTitle:@"电子签章验证码" listTitle:listTitle listContent:listContent ClickOnSure:^(NSString * _Nonnull strSure) {
//        [ws.tableView.mj_header beginRefreshing];
//    } ClickOnCancle:^(NSString * _Nonnull strCancle) {
//
//    }];
//
//    alert.center=self.view.center;
//    WLAlertView * alertView = [[WLAlertView alloc]init];
//    alertView.containerView = alert;
//    alertView.isTouchOtherUndissmiss = YES;
//    [alertView show];

    [[CJAlertViewSign shared]initWithTitle:@"电子签章验证码" listTitle:listTitle listContent:listContent ClickOnSure:^(NSString * _Nonnull strSure) {
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
             [ws.tableView.mj_header beginRefreshing];
        });
        
    } ClickOnCancle:^(NSString * _Nonnull strCancle) {
        
    }];
//    [[CJAlertViewSign shared] show];;
}

#pragma mark ----------非短信验证

- (void)getElecSignTypeWithOrderCode:(NSString *)strCode{
    
    NSString *strURL = CJStringWithFormat(@"%@/ntocc-tps-api/elecSign/%@",CJBaseUrl,strCode);
    NSDictionary *dic = [[NSDictionary alloc]init];
    WS(ws);
    [[HDNetworking sharedHDNetworking] GET:strURL parameters:dic success:^(id  _Nonnull responseObject) {
        
        DLog(@"++++++++%@",responseObject);
        [[CJAlert shared]showStringTitle:@"签章成功" nextStep:^(NSString *strSure) {
            [ws.tableView.mj_header beginRefreshing];
        }];
        
    } failure:^(NSError * _Nonnull error) {
        DLog(@"++++++++%@",error);
        
    }];

}

#pragma mark ----------lazy
- (CJTableView *)tableView{
    if (!_tableView) {
        _tableView = CJTableView.tbInitFrameStyle(CGRectMake(0, kTopHeight + CJTableToTopHeight + header.height, SCREEN_WIDTH, SCREEN_HEIGHT-kTopHeight - CJTableToTopHeight - header.height),UITableViewStylePlain)
        .tbDelegate(self)
        .tbDataSource(self)
        .tbSetOther(YES)
        .tbEstimatedRowHeight(YES)
        .tbMjHeadFooter(YES)
        ;
        WS(ws);
        _tableView.blockMjHeader = ^(BOOL isheader) {
            
            if (isheader) {
                [ws downRefresh];
            } else {
                [ws upRefresh];
            }
        };
    }
    return _tableView;
}

@end
